import React, { Component } from 'react';
import * as common from 'common/common.js';
import { SearchBar, Drawer, Toast, ListView, InputItem  } from 'antd-mobile';
import SeperateLine from 'common/components/SeperateLine.js';

import './GoodsSearch.less';

import * as goodsApi from 'common/api/GoodsApi.js';
import * as userApi from 'common/api/UserApi.js';

/**
 * 商品搜索结果页面
 */
class GoodsSearch extends Component{

	constructor(props) {
		super(props);
		const ds = new ListView.DataSource({
			rowHasChanged: (row1, row2) => row1 !== row2
		});
		this.fetchData = [];
	    this.state = {
			// 分页信息
    	 	pageNo: 1,
    	 	pageTotal: 100,
	      	ds: ds,
	      	isLoading: true,
			height: document.documentElement.clientHeight * 3 / 4,

			// 搜索关键字
			searchType: this.props.params.searchType,
			searchKeyword: this.props.params.searchKeyword ? this.props.params.searchKeyword : "",
			// 排序字段
			goodsSort: {
				sortDirection: "",
				sortKeyword: ""
			},
			// 价格区间
			priceFilter: {
				minPrice: 0,
				maxPrice: 99999999
			},
			inputPrice: {
				minPrice: "",
				maxPrice: ""
			},
			// 筛选框打开状态
			filterOpen: false
		};
	}

	//加入购物车
	addCart = (item) => {
		Toast.loading("", common.TIPS_LOADING_DURATION);
		userApi.addCart({
			memberId: common.userId(),
			goodsId: item.id,
			goodsNum: 1
		}).then(result => {
			Toast.hide();
			if(result.code == common.SUCCESS){
				Toast.info("加入成功", common.TIPS_INFO_DURATION);
			}else{
				Toast.info(result.msg, common.TIPS_INFO_DURATION);
			}
		})
	}

	// 每行渲染的商品item
	renderRow = (item) => {
	    return (
			<div className="goodsItemWrapper">
				<li>
					<img src={item.pic} className="goodsPic" onClick={()=>common.gotoGoodsDetail(item.id)}/>
					<div className="goodsInfo">
						<span className="goodsName" onClick={()=>common.gotoGoodsDetail(item.id)}>{item.name}</span>
						<div className="goodsPriceLine">
							<span className="goodsPrice">￥{common.fenToYuan(item.price)}</span>
							<img onClick={()=>this.addCart(item)} src="assets/img/menu/cart_selected.png" alt=""/>
						</div>
						{/* <span className="shopName">店铺名称店铺名称店铺名称店铺名称<img src="assets/img/right.png"/></span> */}
					</div>
				</li>
				<SeperateLine lineHeight={"0.02rem"} bg={"#f2f2f2"}></SeperateLine>
			</div>
		)
	}

	renderHeader = () => {
		var commonSortClass = this.state.goodsSort.sortKeyword == "" ? "active" : "";

		var priceSortClass = this.state.goodsSort.sortKeyword == "price" ? "active" : "";
		var priceSortImg = this.state.goodsSort.sortDirection == "asc" ? "assets/img/sort/asc.png" : "assets/img/sort/desc.png";

		return (
			<div className="goodsSearch">
				<div className="backHome" onClick={()=>common.gotoUserCart()}>
					<img src="assets/img/menu/cart.png" alt=""/>
				</div>
				{/* 搜索栏 */}
				<div className="search">
					<div className="top">
						<div className="left">
							<img src="assets/img/left.png" onClick={()=>common.goBack()}/>
						</div>
						<div className="content">
							<SearchBar 
								placeholder="搜索商品" 
								value={this.state.searchKeyword} 
								onChange={(val)=>this.setState({searchKeyword:val})}
								showCancelButton
							/>
						</div>
						<div className="right" onClick={()=>this.search()}>
							<span>搜索</span>
						</div>
					</div>
				</div>
				<SeperateLine lineHeight={"0.6rem"}></SeperateLine>
				{/* 排序栏 */}
				<ul className="sortBox">
					<li className={commonSortClass} onClick={()=>this.goodsSort("common")}>
						<span>综合</span>
					</li>
					<li className={priceSortClass} onClick={()=>this.goodsSort("price")}>
						<span>价格</span>
						{
							priceSortClass == "active" &&
							<img src={priceSortImg}/>
						}
					</li>
					<li onClick={()=>this.filterOpen()}>
						<span>筛选</span>
						<img src="assets/img/sort/filter.png"/>
					</li>
				</ul>
				<SeperateLine lineHeight={"0.02rem"} bg={"#f2f2f2"}></SeperateLine>
			</div>
		)
	}
	
	componentDidMount() {
		Toast.loading("", common.TIPS_LOADING_DURATION);
		setTimeout(() => {
			this.refresh();
		}, 500);
	}
	
	refresh = () => {
		const height = document.documentElement.clientHeight;
		goodsApi.goodsList({
			goodsName: this.state.searchKeyword,
			minPrice: this.state.priceFilter.minPrice,
			maxPrice: this.state.priceFilter.maxPrice,
			sortDirection: this.state.goodsSort.sortDirection,
			sortKeyword: this.state.goodsSort.sortKeyword,
			pageNo: this.state.pageNo,
			pageSize: 10
		}).then(result => {
			Toast.hide();
			this.fetchData = [ ...this.fetchData, ...result.data.list];
			var hasMore = result.data.pages > 1 ? true : false;
		  	this.setState({
			  ds: this.state.ds.cloneWithRows(this.fetchData),
			  isLoading: false,
			  height: height,
			  hasMore: hasMore,
			  pageTotal: result.data.totalPage
			});
		})
	}

	// 上拉加载
	onEndReached = (event) => {
		if(this.state.pageNo+1 > this.state.pageTotal){
		  this.setState({
			  hasMore: false
		  })
		  return;
	  }
	  if (this.state.isLoading && !this.state.hasMore) {
			return;
	  }
	  this.setState({ 
			isLoading: true, 
			pageNo: this.state.pageNo + 1
	  });
	  setTimeout(() => {
			goodsApi.goodsList({
				goodsName: this.state.searchKeyword,
				minPrice: this.state.priceFilter.minPrice,
				maxPrice: this.state.priceFilter.maxPrice,
				sortDirection: this.state.goodsSort.sortDirection,
				sortKeyword: this.state.goodsSort.sortKeyword,
				pageNo: this.state.pageNo,
				pageSize: 10
			}).then(result => {
			  this.fetchData = [ ...this.fetchData, ...result.data.list];
			   this.setState({
				  ds: this.state.ds.cloneWithRows(this.fetchData),
				  isLoading: false,
				  hasMore: true
				});
			})
	  }, 500);
	}

	// 商品排序
	goodsSort = (sortKeyword) => {
		if("common" === sortKeyword){
			this.setState({
				goodsSort: {
					sortDirection: "",
					sortKeyword: ""
				}
			}, function(){
				this.search();
			})
		}else{
			var sortDirection = this.state.goodsSort.sortDirection == "desc" ? "asc" : "desc";
			this.setState({
				goodsSort: {
					sortDirection: sortDirection,
					sortKeyword: sortKeyword
				}
			}, function(){
				this.search();
			})
		}
	}

	// 打开筛选框
	filterOpen = () => {
		this.setState({
			filterOpen: true
		})
	}
	// 关闭筛选框 
	filterClose = (...args) => {
		this.setState({
			filterOpen: false
		})
	}
	
	// 搜索事件
	search = (e) => {
		if (e) e.preventDefault();
		document.activeElement.blur();
		setTimeout(() => {
			this.fetchData = [];
			this.setState({
				ds: this.state.ds.cloneWithRows(this.fetchData),
				pageNo: 1,
				pageSize: 10
			}, function(){
				this.refresh();
			})
	  	}, 100);
	}

	// 筛选框
	sidebar() {
		return (
			<div className="filterContent">
				<div className="childBox">
					<div className="childItem">
						<h2>价格区间</h2>
						<div className="inputBox">
							<InputItem
								placeholder="最低价"
								value={this.state.inputPrice.minPrice}
								onChange={(price)=>this.inputPrice(price, 'min')}
							/>
							<span className="separater">--</span>
							<InputItem
								placeholder="最高价"
								value={this.state.inputPrice.maxPrice}
								onChange={(price)=>this.inputPrice(price, 'max')}
							/>
						</div>
					</div>	
				</div>
				<div className="filterSubmit">
					<span onClick={()=>{this.filterReset()}}>重置</span>
					<span onClick={()=>{this.filterSubmit()}}>筛选</span>
				</div>
			</div>
		)	
	}

	inputPrice = (price, type) => {
		if(type == "min"){
			this.setState({
				inputPrice: {
					minPrice: price,
					maxPrice: this.state.inputPrice.maxPrice
				}
			})
		}else{
			this.setState({
				inputPrice: {
					minPrice: this.state.inputPrice.minPrice,
					maxPrice: price
				}
			})
		}
	}

	// 重置
	filterReset = () => {
		this.setState({
			filterOpen: false,
			inputPrice: {
				minPrice: "",
				maxPrice: ""
			},
			priceFilter: {
				minPrice: 0,
				maxPrice: 99999999
			}
		}, function(){
			this.search();			
		})
	}

	// 筛选
	filterSubmit = () => {
		var minPrice = this.state.inputPrice.minPrice ? this.state.inputPrice.minPrice : 0;
		var maxPrice = this.state.inputPrice.maxPrice ? this.state.inputPrice.maxPrice : 99999999;
		this.setState({
			filterOpen: false,
			priceFilter: {
				minPrice: minPrice,
				maxPrice: maxPrice
			}
		}, function(){
			this.search();			
		})
	}

	render(){
		return(
			<Drawer
				className="filter-box"
				style={{ minHeight: document.documentElement.clientHeight }}
				enableDragHandle
				position="right"
				sidebar={this.sidebar()}
				open={this.state.filterOpen}
				onOpenChange={this.filterClose}
				>
				{/* 商品列表 */}
				<ul className="goodsList">
					<ListView
						style={{
						height: this.state.height,
						overflow: 'auto'
						}}
						ref={el => this.lv = el}
						dataSource={this.state.ds}
						renderRow={this.renderRow}
						renderHeader={this.renderHeader}
						renderFooter={() => (
						<div style={{ padding: '0.3rem 0 0.7rem 0', lineHeight: '1rem', textAlign: 'center', fontSize: '0.28rem' }}>
							{
								this.state.hasMore 
								?
									this.state.isLoading
									?
									'加载中...' 
									: 
									'上拉加载'
								:
								'加载完毕'
							}
						</div>
						)}
						renderBodyComponent={() => (
							<div>{this.children}</div>
						)}
						pageSize={100}
						scrollRenderAheadDistance={500}
						onEndReached={this.onEndReached}
						onEndReachedThreshold={10}
					/>
				</ul>
			</Drawer>
		)
	}
}

export default GoodsSearch;